{% extends 'base_pages/base.html' %}

{% block title %}
{{_("Snapshots Management")}}
{% endblock %}

{% block header %}
<h1>{{_("Snapshots Management")}}</h1>
{% endblock %}

{% block content %}
<!-- 下拉菜单选择开发环境 -->
<div class="form-group">
    <label for="devEnvSelect">{{_("Select Development Environment")}}</label>
    <select class="form-control" id="devEnvSelect" onchange="loadSnapshotTree()">
        <option value="">{{_("Choose an environment")}}</option>
        <!-- 动态加载开发环境选项 -->
    </select>
</div>

<!-- 树状结构展示镜像树 -->
<div class="tree">
    <!-- 动态生成树状结构 -->
    <ul id="snapshotTree"></ul>
</div>


<script>
    // 加载开发环境选项
    function loadDevEnvs() {
        apiFetch('/snapshots/get_dev_envs')
            .then(response => response.json())
            .then(data => {
                const select = document.getElementById('devEnvSelect');
                data.forEach(env => {
                    const option = document.createElement('option');
                    option.value = env.name;
                    option.textContent = env.name;
                    select.appendChild(option);
                });


            });
    }

    // 加载快照树
    function loadSnapshotTree() {
        const devEnvName = document.getElementById('devEnvSelect').value;
        if (!devEnvName) return;

        apiFetch(`/snapshots/get_snapshots_and_containers?dev_env_name=${devEnvName}`)
            .then(response => response.json())
            .then(data => {
                updateTree(data.snapshots, data.containers);
            });
    }
    // 更新树状组件
    function updateTree(snapshots_data, containers_data) {
        const treeData = convertToTree(snapshots_data);

        // 打印树状结构
        console.log("treedata", treeData);

        // 构建并显示树状结构
        const treeContainer = document.getElementById('snapshotTree');
        treeContainer.innerHTML = ''; // 清空现有内容

        const containerImagesMap = {}; // image --> container_name

        containers_data.forEach(item => {
            if (!containerImagesMap[item.image]) {
                containerImagesMap[item.image] = [];
            }
            containerImagesMap[item.image].push(item.name);
        });
        console.log("containerImagesMap", containerImagesMap);

        // 生成树状结构
        treeData.forEach(rootNode => {
            treeContainer.appendChild(generateNode(rootNode, containerImagesMap));
        });
    }
    // 将myData转换为树状结构的函数
    // snapshots_data: 快照数据
    // containers_data: 容器数据
    function convertToTree(snapshots_data) {
        // 构建映射表，key为base_image，value为对应的snapshot_image数组
        const map = {};
        const revMap = {};

        snapshots_data.forEach(item => {
            if (!map[item.base_image]) {
                map[item.base_image] = [];
            }
            map[item.base_image].push(item);
            if (!revMap[item.snapshot_image]) {
                revMap[item.snapshot_image] = [];
            }
            revMap[item.snapshot_image].push(item);
        });

        // 查找所有根节点（即没有父节点的节点）
        const rootNodes = [];
        snapshots_data.forEach(item => {
            if (!revMap[item.base_image]) {
                rootNodes.push(item);
            }
        });
        console.log("rootNodes", rootNodes)

        // 递归构建树
        const buildTree = (node) => {
            if (map[node.snapshot_image]) {
                node.children = map[node.snapshot_image].map(child => buildTree(child));
            }
            return node;
        };

        // 为每个根节点构建树
        return rootNodes.map(root => buildTree(root));
    }

    // 创建一个列表项目
    function createListItem(image_name, containerImagesMap) {
        const li = document.createElement('li');
        const liContent = document.createElement('div');
        li.appendChild(liContent);
        // li.textContent = image_name;

        const imageShow = document.createElement('div');
        liContent.textContent = image_name;
        // 为最后一层节点添加按钮
        const button = document.createElement('button');
        button.className = "btn btn-primary btn-sm";
        button.style.marginLeft = "10px";
        button.title = "{{_('Create Container From this Snapshot...')}}"; // 修改为悬浮提示

        // 添加图标
        const icon = document.createElement('img');
        icon.src = "static/svg/new-instance.svg";
        icon.style.width = "16px";
        icon.style.height = "16px";
        icon.style.marginRight = "5px";
        button.appendChild(icon);

        button.onclick = containerFromSnapshotCallbackCreate(image_name);
        const containersShow = document.createElement('div');
        containersShow.textContent = "{{_('Containers:')}} " + containerImagesMap[image_name];
        liContent.appendChild(imageShow);
        liContent.appendChild(containersShow);
        liContent.appendChild(button);
        return li
    }

    // 递归生成树节点
    function generateNode(node, containerImagesMap) {
        const li = createListItem(node.base_image, containerImagesMap) // document.createElement('li');
        /* li.textContent = node.base_image;
        if (containerImagesMap[node.base_image]) {
            li.textContent += " (" + containerImagesMap[node.base_image] + ")";
        }

        // 添加按钮
        const button = document.createElement('button');
        button.textContent = "{{_('Create Container From this Snapshot...')}}";
        button.className = "btn btn-primary btn-sm";
        button.style.marginLeft = "10px";
        button.onclick = containerFromSnapshotCallbackCreate(node.snapshot_image)
        li.appendChild(button); */

        // li.appendChild(createListItem(node.base_image, containerImagesMap));

        if (node.children && node.children.length > 0) {
            const ul = document.createElement('ul');
            node.children.forEach(child => {
                ul.appendChild(generateNode(child, containerImagesMap));
            });
            li.appendChild(ul);
        } else {
            const ul = document.createElement('ul');
            const innerLI = createListItem(node.snapshot_image, containerImagesMap);

            ul.appendChild(innerLI);
            li.appendChild(ul);
        }
        return li;
    }

    function containerFromSnapshotCallbackCreate(snapshot_image) {
        return () => {
            const containerName = prompt("{{_('Enter container name')}}:");
            if (containerName) {
                const devEnvName = document.getElementById('devEnvSelect').value;
                apiFetch('/container_mgr/create_container', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        devEnvName: devEnvName,
                        containerName: containerName,
                        imageName: snapshot_image,
                    }),
                })
                    .then(response => {

                        // 检查响应是否成功（状态码 200-299）
                        if (response.ok) {
                            // 抛出错误，以便进入 catch 分支
                            response.json().then(data => {
                                alert("{{_('Container created successfully')}}");
                            })
                        } else {
                            response.json().then(errorData => {
                                alert("{{_('An error occurred while creating the container')}}:" + errorData.error);
                            })
                        }

                        return response.json();
                    })

            }
        };
    }
    // 页面加载时初始化
    window.onload = () => {
        loadDevEnvs();

        // 测试数据
        let myData = [
            {
                "base_image": "my/ubuntu:22.04",
                "id": 3,
                "snapshot_image": "my/snapshots:myenv--snapshot1"
            },
            {
                "base_image": "my/snapshots:myenv--snapshot1",
                "id": 4,
                "snapshot_image": "my/snapshots:myenv--snapshot2"
            },
            {
                "base_image": "my/snapshots:myenv--snapshot2",
                "id": 5,
                "snapshot_image": "my/snapshots:myenv--snapshot3"
            }
        ];

        updateTree(myData, [
            {
                "name": "mycontainer",
                "image": "my/snapshots:myenv--snapshot3"
            }
        ])
    };
</script>
{% endblock %}